import React, { useState, useRef, useEffect } from 'react';
import { Send, Bot, User, Book, MessageSquare, Brain, CheckCircle, FileText, X, ChevronUp } from 'lucide-react';
import axios from 'axios';
import { API_CONFIG, getApiUrl } from '../config/api';

interface Document {
  id: string;
  title: string;
  content: string;
  source?: string;
  score?: number;
}

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  thinking?: string;
  result?: string;
  documents?: Document[];
  timestamp: Date;
}

interface ChatInterfaceProps {
  selectedModel: string;
}

const ChatInterface: React.FC<ChatInterfaceProps> = ({ selectedModel }) => {
  const [messages, setMessages] = useState<Message[]>([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [chatMode, setChatMode] = useState<'rag' | 'chat'>('rag');
  const [showDocuments, setShowDocuments] = useState(false);
  const [selectedMessageDocs, setSelectedMessageDocs] = useState<Document[]>([]);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 解析思维链内容
  const parseThinkingContent = (content: string) => {
    const thinkRegex = /<think>([\s\S]*?)<\/think>([\s\S]*)/;
    const match = content.match(thinkRegex);
    
    if (match) {
      return {
        thinking: match[1].trim(),
        result: match[2].trim()
      };
    }
    
    return {
      thinking: '',
      result: content
    };
  };

  // 模拟生成检索到的文档（实际项目中应该从后端API获取）
  const generateMockDocuments = (isRagMode: boolean, content: string): Document[] => {
    if (!isRagMode || content.length < 50) return [];
    
    // 模拟检索到的文档
    const mockDocs: Document[] = [
    ];
    
    // 根据内容长度决定返回文档数量
    const docCount = Math.min(mockDocs.length, Math.floor(content.length / 100) + 1);
    return mockDocs.slice(0, docCount);
  };

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleSendMessage = async () => {
    if (!inputMessage.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      role: 'user',
      content: inputMessage,
      timestamp: new Date(),
    };

    setMessages(prev => [...prev, userMessage]);
    setInputMessage('');
    setIsLoading(true);

    try {
      // 根据聊天模式选择正确的模型
      const modelToUse = chatMode === 'rag' ? 'demo-rag' : 'demo-chat';
      
      const requestBody = {
        model: modelToUse,
        messages: [
          {
            role: 'user',
            content: inputMessage
          }
        ],
        stream: true,
        max_tokens: 2000,
        temperature: 0.7
      };

      const response = await fetch(getApiUrl(API_CONFIG.ENDPOINTS.CHAT_COMPLETIONS_STREAM), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
      });

      if (!response.body) {
        throw new Error('No response body');
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      const assistantMessage: Message = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: '',
        timestamp: new Date(),
      };

      setMessages(prev => [...prev, assistantMessage]);

      let buffer = '';
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (line.trim()) {
            // 使用正则表达式去除 'data: ' 前缀，兼容有无前缀的情况
            let eventData = line.replace(/^data:\s*/, '').trim();
            
            if (eventData === '[DONE]' || eventData === '') continue;
            
            try {
              const parsed = JSON.parse(eventData);
              console.log('解析的数据:', parsed); // 调试日志
              
              // 只处理 OpenAI 格式的流式响应
              if (parsed.choices?.[0]?.delta?.content) {
                const content = parsed.choices[0].delta.content;
                console.log('提取的内容:', content); // 调试日志
                
                // 提取文档信息（如果有的话）
                const documentsFromAPI = parsed.documents || [];
                console.log('接收到的文档:', documentsFromAPI); // 调试日志
                
                setMessages(prev => 
                  prev.map(msg => {
                    if (msg.id === assistantMessage.id) {
                      const newContent = msg.content + content;
                      const parsed = parseThinkingContent(newContent);
                      
                      // 使用真实的API文档数据，如果没有则使用模拟数据
                      const documents = documentsFromAPI.length > 0 
                        ? documentsFromAPI.map((doc: any) => ({
                            id: doc.id || `doc-${Date.now()}`,
                            title: doc.title || doc.source || '',
                            content: doc.content || '',
                            source: doc.source || '',
                            score: doc.score || 0.85
                          }))
                        : (chatMode === 'rag' ? generateMockDocuments(true, newContent) : []);
                        
                      return { 
                        ...msg, 
                        content: newContent,
                        thinking: parsed.thinking,
                        result: parsed.result,
                        documents: documents
                      };
                    }
                    return msg;
                  })
                );
              }
            } catch (e) {
              console.warn('解析SSE数据失败:', eventData, e);
              // 不再将解析失败的JSON作为文本处理
            }
          }
        }
      }

    } catch (error) {
      console.error('发送消息失败:', error);
      const errorMessage: Message = {
        id: (Date.now() + 2).toString(),
        role: 'assistant',
        content: '抱歉，发生了错误。请稍后重试。',
        timestamp: new Date(),
      };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const clearMessages = () => {
    setMessages([]);
  };

  return (
    <div className="flex flex-col h-full max-w-4xl mx-auto">
      {/* 模式切换 */}
      <div className="flex items-center justify-between p-4 border-b">
        <div className="flex items-center space-x-4">
          <h2 className="text-xl font-bold text-gray-900">AI 助手</h2>
          <div className="flex items-center space-x-2">
            <button
              onClick={() => setChatMode('rag')}
              className={`
                flex items-center space-x-2 px-3 py-2 rounded-lg transition-colors
                ${chatMode === 'rag' 
                  ? 'bg-blue-100 text-blue-700 border border-blue-300' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }
              `}
            >
              <Book className="w-4 h-4" />
              <span>RAG 问答</span>
            </button>
            <button
              onClick={() => setChatMode('chat')}
              className={`
                flex items-center space-x-2 px-3 py-2 rounded-lg transition-colors
                ${chatMode === 'chat' 
                  ? 'bg-blue-100 text-blue-700 border border-blue-300' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }
              `}
            >
              <MessageSquare className="w-4 h-4" />
              <span>普通聊天</span>
            </button>
          </div>
        </div>
        
        <button
          onClick={clearMessages}
          className="px-3 py-1 text-sm text-gray-600 hover:text-gray-800 border border-gray-300 rounded hover:bg-gray-50"
        >
          清空对话
        </button>
      </div>

      {/* 模式说明 */}
      <div className="p-3 bg-gray-50 border-b">
        <p className="text-sm text-gray-600">
          {chatMode === 'rag' 
            ? '🔍 RAG 模式：基于已上传文档的知识库问答' 
            : '💬 普通聊天：与 AI 自由对话'}
        </p>
      </div>

      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.length === 0 && (
          <div className="text-center text-gray-500 mt-8">
            <div className="mb-4">
              {chatMode === 'rag' ? (
                <Book className="w-12 h-12 mx-auto text-gray-400" />
              ) : (
                <MessageSquare className="w-12 h-12 mx-auto text-gray-400" />
              )}
            </div>
            <p>
              {chatMode === 'rag' 
                ? '开始基于文档的问答吧！' 
                : '开始与 AI 对话吧！'}
            </p>
          </div>
        )}

        {messages.map((message) => (
          <div
            key={message.id}
            className={`flex items-start space-x-3 ${
              message.role === 'user' ? 'justify-end' : 'justify-start'
            }`}
          >
            {message.role === 'assistant' && (
              <div className="flex-shrink-0">
                <div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center">
                  <Bot className="w-5 h-5 text-white" />
                </div>
              </div>
            )}
            
            {message.role === 'user' ? (
              // 用户消息
              <div className="bg-blue-500 text-white px-4 py-2 rounded-lg max-w-xs md:max-w-md lg:max-w-lg xl:max-w-xl">
                <p className="whitespace-pre-wrap">{message.content}</p>
                <div className="text-xs mt-1 text-blue-100">
                  {message.timestamp.toLocaleTimeString()}
                </div>
              </div>
            ) : (
              // 助理消息 - 分别显示思维链和结果
              <div className="max-w-xs md:max-w-md lg:max-w-lg xl:max-w-xl space-y-3">
                {/* 思维链部分 */}
                {message.thinking && (
                  <div className="bg-gradient-to-r from-purple-50 to-indigo-50 border border-purple-200 rounded-lg p-4">
                    <div className="flex items-center space-x-2 mb-2">
                      <Brain className="w-4 h-4 text-purple-600" />
                      <span className="text-sm font-medium text-purple-700">思维过程</span>
                    </div>
                    <div className="text-sm text-purple-800 whitespace-pre-wrap leading-relaxed">
                      {message.thinking}
                    </div>
                  </div>
                )}
                
                {/* 结果部分 */}
                {message.result && (
                  <div className="bg-gray-100 rounded-lg p-4">
                    <div className="flex items-center space-x-2 mb-2">
                      <CheckCircle className="w-4 h-4 text-green-600" />
                      <span className="text-sm font-medium text-gray-700">回答</span>
                    </div>
                    <div className="text-gray-900 whitespace-pre-wrap leading-relaxed">
                      {message.result}
                    </div>
                  </div>
                )}
                
                {/* 如果没有思维链，显示完整内容 */}
                {!message.thinking && !message.result && (
                  <div className="bg-gray-100 rounded-lg p-4">
                    <div className="text-gray-900 whitespace-pre-wrap leading-relaxed">
                      {message.content}
                    </div>
                  </div>
                )}
                
                {/* 时间戳和文档气泡 */}
                <div className="flex items-center justify-between px-2">
                  <div className="text-xs text-gray-500">
                    {message.timestamp.toLocaleTimeString()}
                  </div>
                  
                  {/* 文档气泡 - 只在RAG模式且有文档时显示 */}
                  {chatMode === 'rag' && message.documents && message.documents.length > 0 && (
                    <button
                      onClick={() => {
                        setSelectedMessageDocs(message.documents || []);
                        setShowDocuments(true);
                      }}
                      className="flex items-center space-x-1 px-2 py-1 bg-blue-500 text-white text-xs rounded-full hover:bg-blue-600 transition-colors"
                    >
                      <FileText className="w-3 h-3" />
                      <span>{message.documents.length}</span>
                    </button>
                  )}
                </div>
              </div>
            )}

            {message.role === 'user' && (
              <div className="flex-shrink-0">
                <div className="w-8 h-8 bg-gray-500 rounded-full flex items-center justify-center">
                  <User className="w-5 h-5 text-white" />
                </div>
              </div>
            )}
          </div>
        ))}

        {isLoading && (
          <div className="flex items-start space-x-3">
            <div className="flex-shrink-0">
              <div className="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center">
                <Bot className="w-5 h-5 text-white" />
              </div>
            </div>
            <div className="bg-gray-100 rounded-lg px-4 py-2">
              <div className="flex space-x-1">
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
              </div>
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* 输入区域 */}
      <div className="border-t p-4">
        <div className="flex space-x-3">
          <textarea
            value={inputMessage}
            onChange={(e) => setInputMessage(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder={
              chatMode === 'rag' 
                ? '询问文档相关问题...' 
                : '输入您的消息...'
            }
            className="flex-1 min-h-[44px] max-h-32 p-3 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500"
            disabled={isLoading}
            rows={1}
          />
          <button
            onClick={handleSendMessage}
            disabled={!inputMessage.trim() || isLoading}
            className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center"
          >
            <Send className="w-5 h-5" />
          </button>
        </div>
      </div>
      
      {/* 文档详情弹窗 */}
      {showDocuments && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[80vh] overflow-hidden">
            {/* 弹窗头部 */}
            <div className="flex items-center justify-between p-4 border-b">
              <div className="flex items-center space-x-2">
                <FileText className="w-5 h-5 text-blue-600" />
                <h3 className="text-lg font-semibold">检索到的资料 ({selectedMessageDocs.length})</h3>
              </div>
              <button
                onClick={() => setShowDocuments(false)}
                className="p-1 hover:bg-gray-100 rounded"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            
            {/* 文档列表 */}
            <div className="p-4 overflow-y-auto max-h-[60vh]">
              <div className="space-y-4">
                {selectedMessageDocs.map((doc, index) => (
                  <div key={doc.id} className="border border-gray-200 rounded-lg p-4">
                    <div className="flex items-start justify-between mb-2">
                      <div>
                        <h4 className="font-medium text-gray-900">{doc.title}</h4>
                        <div className="flex items-center space-x-2 text-sm text-gray-500 mt-1">
                          <span>{doc.source}</span>
                          {doc.score && (
                            <>
                              <span>•</span>
                              <span>相关度: {(doc.score * 100).toFixed(0)}%</span>
                            </>
                          )}
                        </div>
                      </div>
                      <div className="text-xs text-gray-400 px-2 py-1 bg-gray-100 rounded">
                        #{index + 1}
                      </div>
                    </div>
                    <div className="text-sm text-gray-700 leading-relaxed">
                      {doc.content}
                    </div>
                  </div>
                ))}
              </div>
            </div>
            
            {/* 弹窗底部 */}
            <div className="border-t p-4 bg-gray-50">
              <div className="flex items-center justify-between">
                <div className="text-sm text-gray-600">
                  这些资料用于生成上述回答
                </div>
                <button
                  onClick={() => setShowDocuments(false)}
                  className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
                >
                  关闭
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ChatInterface; 